﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using com.chttl.ienc.bean;
using DataAccess;

namespace iEN.Immediate
{
    public partial class ShowNowRoom : System.Web.UI.Page
    {

        DataAccess.DBAccess DBAPI = new DataAccess.DBAccess();
        DataAccess.WebService WSAPI = new DataAccess.WebService();

        string strID = "0";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Page.Request.QueryString["ID"] != null)
            {
                strID = this.Page.Request.QueryString["ID"];

                //Create the Row
                //GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
                ////Add the two Columns
                //row.Cells.AddRange(CreateCells());
                //gvMain.Parent.Controls.Add(row);

                if (strID == "-1")
                    strID = "0";

                if (!Page.IsPostBack)
                {
                    Display();

                }

            }
        }

        private void Display()
        {
           
            
            DataTable dtOrg = DBAPI.getOrgGroupTable("1");

            Session["dtOrg"] = dtOrg;

            DataTable dtRoom = dtOrg.Copy();
            DataTable dtFloor = dtOrg.Copy();
            DataTable dtBuilding = dtOrg.Copy();

            dtRoom.DefaultView.RowFilter = "_id ='" + strID + "'";
            dtRoom = dtRoom.DefaultView.ToTable();

            //Get Panel text
            try
            {
                //Get Floor Table
                string strFloorID = dtRoom.Rows[0]["_parent_id"].ToString();
                dtFloor.DefaultView.RowFilter = "_id ='" + strFloorID + "'";
                dtFloor = dtFloor.DefaultView.ToTable();

                //Get Building Table
                string strBuildingID = dtFloor.Rows[0]["_parent_id"].ToString();
                dtBuilding.DefaultView.RowFilter = "_id ='" + strBuildingID + "'";
                dtBuilding = dtBuilding.DefaultView.ToTable();

                //Get Panel text
                if (dtFloor.Rows.Count > 0)
                    Panel1.GroupingText = dtBuilding.Rows[0]["_name"].ToString() + "/" + dtFloor.Rows[0]["_name"].ToString() + "/" + dtRoom.Rows[0]["_name"].ToString();

                lblRoom.Text = dtRoom.Rows[0]["_name"].ToString();
            }
            catch
            {
                Panel1.GroupingText = "";
            }


            string strMsg = "";

            int intErrCount = 0;

            try
            {
                
                //Get Meter table from Device Table
                DataTable dtMeter = DBAPI.getDeviceTable("1");
                dtMeter.DefaultView.RowFilter = "_org_group_id ='" + strID + "'";
                dtMeter = dtMeter.DefaultView.ToTable();
               
                if (dtMeter.Rows.Count < 1)
                {
                    divTable.Visible = false;
                    lblMsg.Text = "此寢室無電錶";
                }
                else
                {
                   
                    int intControlID = int.Parse(dtMeter.Rows[0]["_controller_id"].ToString());
                    lblMeterNum.Text = dtMeter.Rows[0]["_desc"].ToString();
                    //Get kWH, 年月, 日時, 分秒 TagID From TagTable
                    DataTable dtTag = DBAPI.getTagTable("1");
                    DataTable dtTagCopy = dtTag.Copy();
                    dtTag.DefaultView.RowFilter = "_controller_id ='" + intControlID + "' and _device_id='" + dtMeter.Rows[0]["_id"].ToString() + "' and _type='1'";
                    dtTag = dtTag.DefaultView.ToTable();
                    int intkWHTagID = 0;
                    if (dtTag.Rows.Count > 0)
                    {
                        intkWHTagID = int.Parse(dtTag.Rows[0]["_id"].ToString());
                    }
                    dtTagCopy.DefaultView.RowFilter = "_controller_id ='" + intControlID + "' and _device_id='" + dtMeter.Rows[0]["_id"].ToString() + "'";
                    dtTagCopy = dtTagCopy.DefaultView.ToTable();

                    Session["dtTag"] = dtTagCopy;

                    int intYMTagID = 0;
                    int intDHTagID = 0;
                    int intMSTagID = 0;
                    int intRelayTagID = 0;
                    for (int i = 0; i < dtTagCopy.Rows.Count; i++)
                    {
                        switch (dtTagCopy.Rows[i]["_name"].ToString())
                        {
                            case "年月":
                                intYMTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                break;
                            case "日時":
                                intDHTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                break;
                            case "分秒":
                                intMSTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                break;
                            case "Relay狀態":
                                if (dtTagCopy.Rows[i]["_attribute"].ToString() == "AI")
                                    intRelayTagID = int.Parse(dtTagCopy.Rows[i]["_id"].ToString());
                                break;
                        }
                    }

                    //Get Modbus Controler table
                    DataTable dtMControler = DBAPI.getModbusControlerTable();
                    dtMControler.DefaultView.RowFilter = "_id ='" + intControlID + "'";
                    dtMControler = dtMControler.DefaultView.ToTable();

                    string strType = dtMControler.Rows[0]["_connection_type"].ToString();


                    //Get ModBus Information from Modbus Controler and Tag table
                    if (strType == "TCP")
                    {
                        lblIPPort.Text = dtMControler.Rows[0]["_ip"].ToString() + ":" + dtMControler.Rows[0]["_port"].ToString();

                        lblPortName.Text = "--";
                        lblBaudRate.Text = "--";
                        lblParity.Text = "--";
                        lblDataBit.Text = "--";
                        lblStopBit.Text = "--";
                    }
                    else if (strType == "RTU")
                    {
                        lblPortName.Text = dtMControler.Rows[0]["_port_name"].ToString();
                        lblBaudRate.Text = dtMControler.Rows[0]["_baud_rate"].ToString();
                        lblParity.Text = dtMControler.Rows[0]["_parity_check"].ToString();
                        lblDataBit.Text = dtMControler.Rows[0]["_databits"].ToString();
                        lblStopBit.Text = dtMControler.Rows[0]["_stop_bits"].ToString();

                        lblIPPort.Text = "--";
                    }


                    //Get Modbus Tag table
                    DataTable dtMTag = DBAPI.getModbusTagTable();
                    dtMTag.DefaultView.RowFilter = "_id ='" + intkWHTagID + "'";
                    dtMTag = dtMTag.DefaultView.ToTable();
                    lblModbusAdd.Text = dtMTag.Rows[0]["_register_address"].ToString();

                    divTable.Visible = true;

                    //Get RealTime/Relay value
                    string strkWH="";
                    int intYM=0;
                    int intDH = 0;
                    int intMS = 0;
                    string strRelay="";
                    System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();

                    DataObject[] objAry = WSAPI.GetRealtimeTagValue(int.Parse(dtMeter.Rows[0]["_id"].ToString()), "AI");

                    if (objAry == null)
                    {
                        Image1.ImageUrl = "~/images/Red15.gif";
                        lblStatus.Text = "異常";
                        btnRelay.Visible = false;

                            
                    }

                    foreach (TagValue tv in objAry)
                    {
                        int intID = tv.getId();
                        if (intID == intkWHTagID)
                            strkWH = tv.getValue().ToString("f2");
                        if (intID == intYMTagID)
                            intYM = int.Parse(tv.getValue().ToString());
                        if (intID == intDHTagID)
                            intDH = int.Parse(tv.getValue().ToString());
                        if (intID == intMSTagID)
                            intMS = int.Parse(tv.getValue().ToString());
                        if (intID == intRelayTagID)
                            strRelay = tv.getValue().ToString();

                        strMsg = strMsg + "//" + tv.getValue().ToString();
                    }

                    //判斷電錶Relay狀態
                    if (strRelay == "32768")
                    {
                        Image1.ImageUrl = "~/images/Green15.gif";
                        lblStatus.Text = "連線中(供電)";
                        btnRelay.Visible = true;
                        btnRelay.Text = "斷電";
                    }
                    else
                    {
                        Image1.ImageUrl = "~/images/Yellow15.gif";
                        lblStatus.Text = "連線中(斷電)";
                        btnRelay.Visible = true;
                        btnRelay.Text = "供電";

                    }


                    //parsing 年月日, 轉16進位，分為前後各兩碼
                    string strYM = Convert.ToString(intYM, 16);
                    string strDH = Convert.ToString(intDH, 16);
                    string strMS = Convert.ToString(intMS, 16);

                    string strYear = strYM.Substring(0, strYM.Length - 2);
                    string strMonth = strYM.Substring(strYM.Length - 2, 2);
                    string strDay = strDH.Substring(0, strDH.Length - 2);
                    string strHour = strDH.Substring(strDH.Length - 2, 2);
                    string strMin = strMS.Substring(0, strMS.Length - 2);
                    string strSecound = strMS.Substring(strMS.Length - 2, 2);

                    lblkWH.Text = strkWH;
                    lblTime.Text = "20" + strYear + "/" + strMonth + "/" + strDay + " " + strHour + ":" + strMin + ":" + strSecound;

                    btnSyn.CommandArgument = strID;
                    btnRelay.CommandArgument = strID;
                    btnConfirm.CommandArgument = strID;

                    lblMsg.Visible = false;
                }

            }
            catch (Exception e)
            {
                if (intErrCount >= 3)
                {
                    divTable.Visible = false;
                    lblMsg.Text = "無法取得電錶資料，請稍後再試，或連絡系統管理者<br>" + e.Message + "<br>" + strMsg;
                    lblMsg.Visible = true;
                }
                else
                {
                    intErrCount = intErrCount + 1;
                    System.Threading.Thread.Sleep(3000);
                    Display();
                }
            }

        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            Display();
        }

        protected void btnSyn_Click(object sender, EventArgs e)
        {
            Button btnSyn = (Button)sender;
            string strID = btnSyn.CommandArgument;

            DataTable dtLog = (DataTable)Session["dtOrg"];
            dtLog.DefaultView.RowFilter = "_id ='" + strID + "'";
            dtLog = dtLog.DefaultView.ToTable();

            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有修改設定的權限！')", true);
                return;
            }

            try
            {

                DataTable dtTage = (DataTable)Session["dtTag"];

                int intYMTagID = 0;
                int intDHTagID = 0;
                int intMSTagID = 0;
                for (int i = 0; i < dtTage.Rows.Count; i++)
                {
                    switch (dtTage.Rows[i]["_name"].ToString())
                    {
                        case "年月設定":
                            intYMTagID = int.Parse(dtTage.Rows[i]["_id"].ToString());
                            break;
                        case "日時設定":
                            intDHTagID = int.Parse(dtTage.Rows[i]["_id"].ToString());
                            break;
                        case "分秒設定":
                            intMSTagID = int.Parse(dtTage.Rows[i]["_id"].ToString());
                            break;
                    }
                }

                DateTime dtNow = DateTime.Now;

                string strNow = dtNow.ToString("yyyy/MM/dd HH:mm:ss");

                string strYM = strNow.Substring(2, 2) + strNow.Substring(5, 2);
                string strDH = strNow.Substring(8, 2) + strNow.Substring(11, 2);
                string strMS = strNow.Substring(14, 2) + strNow.Substring(17, 2);
                int intYM = Convert.ToInt32(strYM, 16);
                int intDH = Convert.ToInt32(strDH, 16);
                int intMS = Convert.ToInt32(strMS, 16);

                Boolean blnResultYM = WSAPI.SetTagValue(int.Parse(dtTage.Rows[0]["_device_id"].ToString()), intYMTagID, intYM);
                Boolean blnResultDH = WSAPI.SetTagValue(int.Parse(dtTage.Rows[0]["_device_id"].ToString()), intDHTagID, intDH);
                Boolean blnResultMS = WSAPI.SetTagValue(int.Parse(dtTage.Rows[0]["_device_id"].ToString()), intMSTagID, intMS);

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "寢名稱：" + dtLog.Rows[0]["_name"].ToString();

                if (blnResultYM && blnResultDH && blnResultMS)
                {
                    new DBAccess().addEventLog(strAccount, strIP, 106, strMemo, "1", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶時間同步成功！')", true);
                }
                else
                {
                    new DBAccess().addEventLog(strAccount, strIP, 106, strMemo, "0", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶時間同步失敗！')", true);
                }

                Display();
            }
            catch
            {
                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                new DBAccess().addEventLog(strAccount, strIP, 106, "", "0", int.Parse(strID));

                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶時間同步失敗！')", true);
            }
        }

        protected void btnRelay_Click(object sender, EventArgs e)
        {
            Button btnSyn = (Button)sender;
            string strID = btnSyn.CommandArgument;

            DataTable dtLog = (DataTable)Session["dtOrg"];
            dtLog.DefaultView.RowFilter = "_id ='" + strID + "'";
            dtLog = dtLog.DefaultView.ToTable();
            
            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有修改設定的權限！')", true);
                return;
            }
            
            try
            {
                DataTable dtTage = (DataTable)Session["dtTag"];

                int intRelyTagID = 0;

                for (int i = 0; i < dtTage.Rows.Count; i++)
                {
                    switch (dtTage.Rows[i]["_name"].ToString())
                    {
                        case "Relay狀態":
                            if (dtTage.Rows[i]["_attribute"].ToString() == "AO")
                                intRelyTagID = int.Parse(dtTage.Rows[i]["_id"].ToString());
                            break;

                    }
                }
                int intRelay = 32768;
                int intEvent = 105;
                if (btnRelay.Text == "斷電")
                {
                    intRelay = 0;
                    intEvent = 105;
                }
                else if (btnRelay.Text == "供電")
                {
                    intRelay = 32768;
                    intEvent = 106;
                }

                Boolean blnResult = WSAPI.SetTagValue(int.Parse(dtTage.Rows[0]["_device_id"].ToString()), intRelyTagID, intRelay);

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "寢室名稱：" + dtLog.Rows[0]["_name"].ToString();

                if (blnResult)
                {
                    new DBAccess().addEventLog(strAccount, strIP, intEvent, strMemo, "1", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶供電控制修改成功！')", true);
                }
                else
                {
                    new DBAccess().addEventLog(strAccount, strIP, intEvent, strMemo, "0", int.Parse(strID));
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶供電控制修改失敗！')", true);
                }

                Display();
            }
            catch
            {

                int intEvent = 105;
                if (btnRelay.Text == "斷電")
                    intEvent = 105;
                else if (btnRelay.Text == "供電")
                    intEvent = 106;

                string strAccount = Session["LoginAccount"].ToString();
                string strIP = Session["LoginIP"].ToString();
                string strMemo = "寢名稱：" + dtLog.Rows[0]["_name"].ToString();

                new DBAccess().addEventLog(strAccount, strIP, intEvent, strMemo, "0", int.Parse(strID));
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶供電控制修改失敗！')", true);
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            divComfirm.Visible = true;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            divComfirm.Visible = false;
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            Button btnSyn = (Button)sender;
            string strID = btnSyn.CommandArgument;

            DataTable dtLog = (DataTable)Session["dtOrg"];
            dtLog.DefaultView.RowFilter = "_id ='" + strID + "'";
            dtLog = dtLog.DefaultView.ToTable();

            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有修改設定的權限！')", true);
                return;
            }
            
            try
            {

                DataTable dtUser = new DBAccess().getUserData("1");
                dtUser.DefaultView.RowFilter = "_account= '" + Session["LoginAccount"].ToString() + "' and _password='" + tbPwd.Text + "'";
                dtUser = dtUser.DefaultView.ToTable();


                if (dtUser.Rows.Count > 0)
                {
                    DataTable dtTage = (DataTable)Session["dtTag"];

                    int intRelyTagID = 0;

                    for (int i = 0; i < dtTage.Rows.Count; i++)
                    {
                        switch (dtTage.Rows[i]["_name"].ToString())
                        {
                            case "電表Reset":
                                if (dtTage.Rows[i]["_attribute"].ToString() == "AO")
                                    intRelyTagID = int.Parse(dtTage.Rows[i]["_id"].ToString());
                                break;

                        }
                    }

                    int intReset = 26214;

                    Boolean blnResult = WSAPI.SetTagValue(int.Parse(dtTage.Rows[0]["_device_id"].ToString()), intRelyTagID, intReset);

                    string strAccount = Session["LoginAccount"].ToString();
                    string strIP = Session["LoginIP"].ToString();
                    string strMemo = "寢名稱：" + dtLog.Rows[0]["_name"].ToString();

                    if (blnResult)
                    {
                        new DBAccess().addEventLog(strAccount, strIP, 104, strMemo, "1", int.Parse(strID));
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶歸零成功！')", true);
                        divComfirm.Visible = false;
                    }
                    else
                    {
                        new DBAccess().addEventLog(strAccount, strIP, 104, strMemo, "0", int.Parse(strID));
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶歸零失敗！')", true);
                    }

                    Display();
                }
                else
                {
                    string strAccount = Session["LoginAccount"].ToString();
                    string strIP = Session["LoginIP"].ToString();
                    new DBAccess().addEventLog(strAccount, strIP, 104, "", "0", int.Parse(strID));

                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('密碼認證錯誤！')", true);

                }

            }
            catch
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('電錶歸零失敗！')", true);
            }
        }


        

    }
}